package com.ktjy.config;

import com.ktjy.cond.ConditionOnPropertyEnable;
import com.ktjy.entity.SysRole;
import com.ktjy.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.ktjy.service")
@PropertySource(value = "classpath:user.properties", encoding = "utf-8")
@EnableAspectJAutoProxy  //开启aop注解的支持
@EnableTransactionManagement //开启事务注解的支持
public class JavaConfig {
    //    @Autowired
//    private Environment env;
    @Value("${user.realName}")
    private String realName;

    @Value("${user.account}")
    private String account;

    @Value("${user.password}")
    private String password;

    @Value("${user.sex}")
    private Long sex;

    @Bean
    public SysUser user(SysRole role) {
        SysUser user = new SysUser();
        user.setRealName(realName);
        user.setAccount(account);
        user.setPassword(password);
        user.setSex(sex);
        user.setRole(role);
        return user;
    }

    /**
     * 管理员角色
     *
     * @return
     */
//    @Primary
    @Bean
    @Conditional(ConditionOnPropertyEnable.OnEnableCondition.class)
    //表示当配置文件中admin.enable=true时,才需要创建adminRole的bean
    @ConditionOnPropertyEnable(enableProperty = "admin.enable")
    public SysRole adminRole() {
        SysRole role = new SysRole();
        role.setId(1L);
        role.setRoleName("管理员");
        role.setCode("ADMIN");
        return role;
    }

    /**
     * 店长角色
     *
     * @return
     */
    @Bean
    //传入ConditionOnPropertyEnable注解接口中的实现了Condition的内部类的全限定名
    @Conditional(ConditionOnPropertyEnable.OnEnableCondition.class)
    //表示当配置文件中manager.enable=true时,才需要创建managerRole的bean
    @ConditionOnPropertyEnable(enableProperty = "manager.enable")
    public SysRole managerRole() {
        SysRole role = new SysRole();
        role.setId(2L);
        role.setRoleName("店长");
        role.setCode("MANAGER");
        return role;
    }

    /**
     * 事务管理器
     */
    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}
